<template>
    <div class="mainContent">
        <path-tracking :path='path' />
        <div class="pageContent">

            <basic-infos 
                ref="basicInfo"
                origin="server"
                pageType='edit'
            />
            
            <custom-tag 
                ref="customTag"
                title='客户标签'
            />
            
            <div class="tableTitle">
                <div class="tableIcon"><img src="@/assets/img/flower_brown.png"></div>
                <div class="tableText">跟进人</div>
            </div>
            <div class="bgBox">
                <div style="padding-bottom: 1rem;" ref="followUpBy">
                    <el-select
                        size="small"
                        v-model="followUpBy"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词"
                        :remote-method="remoteMethod"
                        :loading="loading"
                    >
                        <el-option
                            v-for="item in followUpList"
                            :key="item.id"
                            :label="item.userName"
                            :value="item.sapUserId"
                        />
                    </el-select>
                </div>
            </div>
  
            <div class="tableTitle">
                <div class="tableIcon"></div>
                <div class="tableText">备注：</div>
            </div>
            <div class="bgBox">
                <div style="padding-bottom: 1rem;">
                    <el-input type='textarea' rows="5" style="width: 100%;resize: none;" v-model="remarks">

                    </el-input>
                </div>
            </div>
            <!-- 按钮 -->
            <div class="btnsCan">
                <div class="btnLayout">
                    <div class="btn" @click="doSave(1)">保存</div>
                    <div class="btn cancel" @click="doCancel">取消</div>
                </div>
            </div>
        </div>
        <verify-filed-popup 
            ref="verifyPopup"
            @doSave="doSave"
        />
    </div>
</template>
<script>
    import datas from '../datas.js'
    import pathTracking from '@/components/common/pathTracking'
    import advancedSearch from '@/components/common/filter/advancedSearch.vue'
    import customTag from '../../component/customTag'
    import verifyFiledPopup from '../verifyFiledPopup'
    import basicInfos from '../../component/basicInfos'
    import { createOrder, modifyOrder, getFollowUpList, findStaffByName, doDistribute, getDistribute } from '../axios.js'
    import { getDetail } from '../../component/seeDetail/axios.js'
    import verifyResult from '../../component/verifyResult'
    export default {
        name: 'operateOrder',
        data() {
            return {
                path: ['CRM', '预约管理', {label: '预约审核', name: 'bookedCustomer'}, '编辑'],
                dialogView: false,
                // input配置
                scheduleOption: datas.createScheduleOption,
                // 之前的数据
                previousData: {},
                previousFollow: '',
                remarks: '',
                followUpBy: '',
                followUpList: [],
                loading: false
            }
        },
        components: {
            verifyFiledPopup,
            advancedSearch,
            pathTracking,
            verifyResult,
            basicInfos,
            customTag
        },
        methods: {
            // 存
            doSave(status) {
                // 详细信息
                let basicInfo = this.$refs.basicInfo.getResult();
                // 标签
                let tags = this.$refs.customTag.getResult();
                if(!basicInfo || !tags) {
                    return
                }
                // 编辑/审核时需要把id传回去
                basicInfo.id = this.previousData.id

                // 客户标签
                basicInfo.systemTagCategoryVO = tags;
                basicInfo.followUpRecords = [];

                // 备注
                let obj = {
                    content: this.remarks, 
                    type: 1
                }
                // 编辑时需要加上跟进人
                !this.followUpBy ? this.$refs.followUpBy.classList.add('qxz_redInput') : this.$refs.followUpBy.classList.remove('qxz_redInput')
                if(!this.followUpBy) {
                    return
                }
                if(!/^[ ]*$/.test(this.remarks)) {
                    basicInfo.followUpRecords.push(obj)
                }
                basicInfo.status = status;
                // 客服创建的就是1，到店就是2
                basicInfo.type = 1;
                // 对比数据
                let modified = false
                // 判断基础数据是否改动
                Object.keys(basicInfo).map(ele => {
                    if(!this.isObj(this.previousData[ele]) && !Array.isArray(this.previousData[ele])) {
                        basicInfo[ele] != this.previousData[ele] && (modified = true)
                        basicInfo[ele] != this.previousData[ele] && console.log(ele, basicInfo[ele], this.previousData[ele], basicInfo[ele] != this.previousData[ele], 'sssssss')
                    }
                })
                // 标签是否改动
                JSON.stringify(this.previousData.systemTagCategoryVO) != JSON.stringify(tags) && (modified = true)
                // 跟进人是否改动
                this.previousFollow != this.followUpBy && (modified = true)
                if(!modified) {
                    this.$message({
                        message: '没有修改，无需保存',
                        type: 'warning'
                    })
                    return
                }
                let followObj = {
                    assignIds: [this.followUpBy],
                    reservationIds: [this.previousData.id]
                }
                // 跟进人实际是指派，调用指派接口
                doDistribute(followObj).then(res => {
                    if(res.data.status === 200) {
                        basicInfo.isAssign = 1
                        // 修改
                        modifyOrder(basicInfo).then(res => {
                            if(res.data.status === 200) {
                                this.$message({
                                    showClose: true,
                                    message: '编辑成功',
                                    type: 'success'
                                });
                                this.sucCallback()
                            }
                        }).catch(err => {
                            console.log('err: ', err)
                        })
                    }else {
                        this.$message({
                            type: 'error',
                            message: '指派跟进人失败'
                        })
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
                
            },
            isObj(param) {
                return Object.prototype.toString.call(param) === "[object Object]"
            },
            sucCallback() {
                this.$refs.basicInfo.clearInput();
                this.$router.replace({name: 'bookedCustomer'})
            },
            doCancel() {
                this.$router.replace({name: 'bookedCustomer'})
            },
            // 清空输入框中的内容
            clearInputs() {
                this.$refs.basicInfo.clearInput();
                this.$refs.customTag.clearInput();
            },
            // 审核失败
            verifyFiled() {
                this.$refs.verifyPopup.openBox();
            },
            // 获取详情分发数据
            getDetail() {
                let searchKey = this.$route.query.searchKey
                // 显示上次的跟进人
                searchKey && getDistribute(searchKey).then(res => {
                    if(res.data.status === 200) {
                        this.followUpBy = res.data.result.sapUserId
                        this.previousFollow = res.data.result.sapUserId
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
                // 获取回显数据
                searchKey && getDetail(searchKey).then(res => {
                    if(res.data.status === 200) {
                        this.previousData = res.data.result;
                        // 给组件数据
                        this.$refs.basicInfo.dispatchData(res.data.result)
                        this.$refs.customTag.dispatchData(res.data.result)
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
            },
            // 获取跟进人列表
            getFollowUp() {
                getFollowUpList().then(res => {
                    if(res.data.status === 200) {
                        let arr = [{
                            label: '请选择创建人',
                            value: undefined
                        }]
                        res.data.result.map(ele => {
                            arr = arr.concat(ele)
                        })
                        this.followUpList = arr
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
            },
            remoteMethod(clue) {
                findStaffByName(clue).then(res => {
                    if(res.data.status === 200) {
                        let arr = []
                        res.data.result.map(ele => {
                            arr = arr.concat(ele)
                        })
                        this.followUpList = arr
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
            }
        },
        mounted() {
            this.getFollowUp()
        },
        activated() {
            this.getDetail()
        }
    }
</script>
<style scoped>
    .pageContent{
        padding: 16px;
        min-width: 58rem;
    }
    .tableTitle{
        height: 4rem;
        display: flex;
        align-items: center;
        flex-direction: row;
        justify-content: flex-start;
        background: #FFF;
    }
    .tableIcon{
        width: .4rem;
        margin-left: 1rem;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .tableText{
        height: 100%;
        line-height: 4rem;
        margin-left: 0.4rem;
        font-size: 14px;
        font-weight: bold;
        color: #715D4A;
    }
    .couple{
        width: 30rem;
        display: flex;
        height: 4rem;
        font-size: 1.4rem;
        align-items: center;
        justify-content: center;
        color: #222222;
    }
    .lines{
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .btnsCan{
        background: #FFF;
        padding: 1.5rem 0;
    }
    .btnLayout{
        text-align: center;
    }
    .btn{
        display: inline-block;
        width: 120px;
        height: 40px;
        border-radius: 20px;
        background: #7e6b5a;
        text-align: center;
        line-height: 40px;
        color: #FFF;
        font-size: 14px;
        cursor: pointer;
        margin: 0 8px;
    }
    .cancel{
        background: #000;
    }
    .bgBox{
        background: #FFF;
        padding: 0 2.4rem;
    }
</style>